package cz.muni.fi.pa165.musiclibrary.musiclibraryws.converter;

import java.io.Serializable;
import java.util.Set;

import org.reflections.Reflections;

import cz.muni.fi.pa165.musiclibrary.api.service.dto.IDTOObject;

/**
 * Factory for creating DTO instances.
 * 
 * @author Maros Kucbel
 * @date 2012-11-25T16:47:31+0100
 */
public final class DTOFactory implements Serializable {

    /**
     * Creates new instance of given class.
     * @param <T> Interface type that extends {@link IDTOObject}.
     * @param clazz Class.
     * @return New instance of given interface.
     */
    public static <T extends IDTOObject> T create(Class<T> clazz) {
        Reflections reflections = new Reflections("cz.muni.fi.pa165.musiclibrary");
        Set<Class<? extends T>> subTypesOf = reflections.getSubTypesOf(clazz);
        for (final Class<? extends T> cl : subTypesOf) {
            if (cl.isInterface()) {
                continue;
            }
            try {
                return cl.newInstance();
            } catch (final IllegalAccessException ex) {
                continue;
            } catch (final InstantiationException ex) {
                continue;
            }
        }
        throw new IllegalStateException(String.format("No implementing class of interface [%1$s] found.", clazz));
    }
}